package com.whzykj.resource;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.google.common.collect.Lists;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.whzykj.common.Consts;
import com.whzykj.common.DictCache;
import com.whzykj.common.ReturnB2BEnum;
import com.whzykj.common.ReturnEnum;

import net.sf.json.JSONObject;
import com.whzykj.common.JsonUtil;
import com.whzykj.model.Shopping;

public class GoodsResource {
	
	/****
	 * 商品列表
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'list',station_id:'3'}
	 */
	public void list(JSONObject messageObj, JSONObject result) {
		
	    Object goods_kind = messageObj.get("goods_kind");
	    Object station_id = messageObj.get("station_id");
		
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT a.goods_id,app_name,img_url,goods_kind,goods_place,a.GOODS_SPEC,goods_packing,discount_desc,b.MINUS_PRICE,b.SALE_PRICE,b.UNIT_PRICE,c.STORE_NUM,c.SALE_NUM FROM goodsinfo a,PRICE b,STORE c  ");
		sbf.append(" WHERE a.GOODS_STATUS='1' AND a.GOODS_ID=b.GOODS_ID AND a.GOODS_ID=c.GOODS_ID and date(b.set_date) = curdate() and date(c.set_date) = curdate()  ");
		if(goods_kind != null && !"".equals(goods_kind))
		{
			sbf.append(" and a.goods_kind='"+goods_kind.toString()+"' ");
		}
		if(station_id != null && !"".equals(station_id))
		{
			sbf.append(" and b.station_id="+station_id.toString()+" ");
		}
		try {
			List<Record> list = Db.find(sbf.toString());
			if(list.size()>0)
			{
				goodsSetValue(list);
				result.put("data", JsonKit.toJson(list));
				JsonUtil.put(result, ReturnEnum.GOODS_LIST_SUCCESS);
			}else{
				
				StringBuffer sbf1 = new StringBuffer();
				sbf1.append(" SELECT a.goods_id,app_name,img_url,goods_kind,goods_place,a.GOODS_SPEC,goods_packing,discount_desc,b.MINUS_PRICE,b.SALE_PRICE,b.UNIT_PRICE,c.STORE_NUM,c.SALE_NUM FROM goodsinfo a,PRICE b,STORE c  ");
				sbf1.append(" WHERE a.GOODS_STATUS='1' AND a.GOODS_ID=b.GOODS_ID AND a.GOODS_ID=c.GOODS_ID and date(b.set_date) = curdate() and date(c.set_date) = curdate()  ");
				if(goods_kind != null && !"".equals(goods_kind))
				{
					sbf1.append(" and a.goods_kind='"+goods_kind.toString()+"' ");
				}
				sbf1.append(" and b.station_id=-1 ");
				List<Record> list1 = Db.find(sbf1.toString());
				
				goodsSetValue(list1);
				
				result.put("data", JsonKit.toJson(list));
				JsonUtil.put(result, ReturnEnum.GOODS_LIST_SUCCESS);
			}
		} catch (Exception e) {
			// log.error(e.getLocalizedMessage(),e);
			result.put("data", Lists.newArrayList());
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
		}
	}
	
	public void goodsSetValue(List<Record> list){
		for(Record rd:list)
		{
			String goodspacking=rd.getStr("goods_packing");
			String goodsspckname = DictCache.cache.getDicByText(goodspacking);
			rd.set("goods_packing_name", goodsspckname);//商品包装
            int goods_spec=rd.getInt("goods_spec");
            rd.set("goods_spec_name", goods_spec+"斤装");//商品包装
            
            String goodskind=rd.getStr("goods_kind");
            String goodskindname = DictCache.cache.getDicByText(goodskind);
            rd.set("goodskindname", goodskindname);//商品包装
            
            BigDecimal sale_price= rd.getBigDecimal("sale_price");
            rd.set("sale_price_name", "￥"+sale_price+"/件");//商品包装
            BigDecimal unit_price= rd.getBigDecimal("unit_price");
            rd.set("unit_price_name", "￥"+unit_price+"/斤");//商品包装
            
            int store_num = rd.getInt("store_num");
            int sale_num = rd.getInt("sale_num");
            rd.set("stock", store_num-sale_num);//商品包装
            
            String discount_desc = rd.getStr("discount_desc");
            if(discount_desc == null || "".equals(discount_desc))
            {
            	rd.set("discount_desc", "");
            }
		}
	}
	
	/****
	 * 热推商品
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'recommend',station_id:6}
	 */
	public void recommend(JSONObject messageObj, JSONObject result){
		Object station_id = messageObj.get("station_id");
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT c.REC_NAME,a.img_url,goods_packing,b.MINUS_PRICE,b.SALE_PRICE,b.UNIT_PRICE FROM goodsinfo a,PRICE b,recommend c  ");
		sbf.append(" WHERE a.GOODS_STATUS='1' AND a.GOODS_ID=b.GOODS_ID AND a.GOODS_ID=c.GOODS_ID AND c.REC_ORDER IN (1,2,3) and date(b.set_date) = curdate() ");
		if(station_id != null && !"".equals(station_id))
		{
			sbf.append(" and b.STATION_ID="+station_id.toString()+" ");
		}
		sbf.append(" group by a.goods_id ");
		try {
			List<Record> list = Db.find(sbf.toString());
			if(list.size()>0)
			{
				for(Record rd:list)
				{
                    BigDecimal sale_price= rd.getBigDecimal("sale_price");
                    rd.set("sale_price_name", "￥"+sale_price+"/件");//商品包装
				}
				result.put("data", JsonKit.toJson(list));
				JsonUtil.put(result, ReturnEnum.RECOMMEND_SUCCESS);
			}else{
				JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS_NODATA);
			}
		} catch (Exception e) {
			// log.error(e.getLocalizedMessage(),e);
			result.put("data", Lists.newArrayList());
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
		}
	}
	
	/****
	 * 热推商品列表
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'recommendlist',station_id:6}
	 */
	public void recommendlist(JSONObject messageObj, JSONObject result){
		
		Object station_id = messageObj.get("station_id");
		
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT a.goods_id,app_name,img_url,goods_place,a.GOODS_SPEC,goods_packing,discount_desc,b.MINUS_PRICE,b.SALE_PRICE,b.UNIT_PRICE,c.STORE_NUM,c.SALE_NUM FROM goodsinfo a,PRICE b,STORE c,recommend d  ");
		sbf.append(" WHERE a.GOODS_STATUS='1' AND a.GOODS_ID=b.GOODS_ID AND a.GOODS_ID=c.GOODS_ID AND a.GOODS_ID=d.GOODS_ID AND d.REC_ORDER IN (1,2,3) and date(b.set_date) = curdate() and date(c.set_date) = curdate()  ");
		if(station_id != null && !"".equals(station_id)){
			sbf.append(" and b.STATION_ID="+station_id.toString()+" ");
		}
		sbf.append(" group by a.goods_id");
		try {
			List<Record> list = Db.find(sbf.toString());
			if(list.size()>0)
			{
				for(Record rd:list)
				{
					String goodspacking=rd.getStr("goods_packing");
					String goodsspckname = DictCache.cache.getDicByText(goodspacking);
					rd.set("goods_packing_name", goodsspckname);//商品包装
                    int goods_spec=rd.getInt("goods_spec");
                    rd.set("goods_spec_name", goods_spec+"斤装");//商品包装
                    
                    BigDecimal sale_price= rd.getBigDecimal("sale_price");
                    rd.set("sale_price_name", "￥"+sale_price+"/件");//商品包装
                    BigDecimal unit_price= rd.getBigDecimal("unit_price");
                    rd.set("unit_price_name", "￥"+unit_price+"/斤");//商品包装
                    
                    int store_num = rd.getInt("store_num");
                    int sale_num = rd.getInt("sale_num");
                    rd.set("stock", store_num-sale_num);//商品包装
                    if(rd.getStr("discount_desc")==null){
                    	rd.set("discount_desc", "");
                    }
				}
				result.put("data", JsonKit.toJson(list));
				JsonUtil.put(result, ReturnEnum.RECOMMEND_LIST_SUCCESS);
			}else{
				JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS_NODATA);
			}
		} catch (Exception e) {
			// log.error(e.getLocalizedMessage(),e);
			result.put("data", Lists.newArrayList());
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
		}
	}
	
	/****
	 * 添加商品到购物车
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'addshopping',user_id:'1',goods_id:'1',num:"3"}
	 */
	public void addshopping(JSONObject messageObj, JSONObject result){
		String user_id=messageObj.getString("user_id");
		String goods_id=messageObj.getString("goods_id");
		String num=messageObj.getString("num");
		Shopping shopp =Shopping.me.getShopp(goods_id, user_id);
		if(shopp != null)
		{
			int nums=shopp.getInt("num");
			shopp.set("num", Integer.parseInt(num)+nums);
			shopp.update();
		}else{
			Shopping shopping =new Shopping();
			shopping.set("user_id", user_id);
			shopping.set("goods_id", goods_id);
			shopping.set("num", num);
			shopping.set("status", Consts.TRUE);
			shopping.set("create_date", new Date());
			shopping.save();
		}
		JsonUtil.put(result, ReturnEnum.SHOPPING_ADD_SUCCESS);
	}
	
	/****
	 * 添加商品到购物车
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'shopping',user_id:'1'}
	 */
	public void shopping(JSONObject messageObj, JSONObject result){
		String user_id=messageObj.getString("user_id");
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT a.goods_id,app_name,img_url,goods_place,a.GOODS_SPEC,goods_packing,discount_desc,b.MINUS_PRICE,b.SALE_PRICE,b.UNIT_PRICE,d.num FROM goodsinfo a,PRICE b,STORE c,shopping d  ");
		sbf.append(" WHERE a.GOODS_STATUS='1' AND a.GOODS_ID=b.GOODS_ID AND a.GOODS_ID=c.GOODS_ID and a.goods_id=d.goods_id and d.user_id=? ");
		try {
			List<Record> list = Db.find(sbf.toString(),user_id);
			if(list.size()>0)
			{
				for(Record rd:list)
				{
					String goodspacking=rd.getStr("goods_packing");
					String goodsspckname = DictCache.cache.getDicByText(goodspacking);
					rd.set("goods_packing_name", goodsspckname);//商品包装
                    int goods_spec=rd.getInt("goods_spec");
                    rd.set("goods_spec_name", goods_spec+"斤装");//商品包装
                    
                    BigDecimal sale_price= rd.getBigDecimal("sale_price");
                    rd.set("sale_price_name", "￥"+sale_price+"/件");//商品包装
                    BigDecimal unit_price= rd.getBigDecimal("unit_price");
                    rd.set("unit_price_name", "￥"+unit_price+"/斤");//商品包装
                    
				}
				result.put("data", JsonKit.toJson(list));
				JsonUtil.put(result, ReturnEnum.SHOPPING_LIST_SUCCESS);
			}else{
				JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS_NODATA);
			}
		} catch (Exception e) {
			// log.error(e.getLocalizedMessage(),e);
			result.put("data", Lists.newArrayList());
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
		}
	}
	
	/**
	 * 菜篮子中查询所有商品的信息（含实时的库存和价格）
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'findgoodslist',station_id:'1'}
	 * http://112.124.127.38:8081/bcy/mobile/Interface?content={namespace:'goods',type:'findgoodslist',station_id:'1'}
	 */
	public void findgoodslist(JSONObject messageObj, JSONObject result){
		String station_id=messageObj.getString("station_id");
		if(station_id==null || station_id.equals("")){
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
			return;		
		}
		StringBuffer sb=new StringBuffer(" SELECT gi.GOODS_ID,gi.GOODS_NAME,gi.APP_NAME,gi.IMG_URL,gi.GOODS_PLACE,");
		sb.append(" CONCAT(gi.GOODS_SPEC,'斤装') as GOODS_SPEC,dict.DICT_NAME,p.SALE_PRICE,(s.STORE_NUM-s.SALE_NUM) as STORE_NUM");
		sb.append(" from goodsinfo gi");
		sb.append(" inner JOIN dictionary dict on dict.DICT_CODE=gi.GOODS_PACKING");
		sb.append(" inner JOIN price p on gi.GOODS_ID=p.GOODS_ID");
		sb.append(" inner JOIN store s on s.GOODS_ID=gi.GOODS_ID");
		sb.append(" where TO_DAYS(p.SET_DATE)=TO_DAYS(NOW()) AND TO_DAYS(s.SET_DATE)=TO_DAYS(NOW())");
		sb.append(" AND p.STATION_ID="+station_id);
		try{
			List<Record> list = Db.find(sb.toString());
			result.put("data", JsonKit.toJson(list));
			JsonUtil.put(result, ReturnEnum.GOODS_LIST_SUCCESS);
		}catch(Exception ex){
			result.put("data", Lists.newArrayList());
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
		}
	}
	
	/**
	 * 菜篮子中查询所有商品的信息（含实时的库存和价格）,需要传入station_id 和goods_ids的集合
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'findgoodsinfo',station_id:'1',goods_id:'1'}
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'findgoodsinfo',station_id:'1',goods_ids:'1,2,3'}
	 * 
	 */
	public void findgoodsinfo(JSONObject messageObj, JSONObject result){
		String station_id=messageObj.getString("station_id");
		String goods_ids=messageObj.getString("goods_ids");
		if(station_id==null || station_id.equals("") || goods_ids==null || goods_ids.equals("")){
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
			return;		
		}
		StringBuffer sb=new StringBuffer(" SELECT gi.GOODS_ID,gi.GOODS_NAME,gi.APP_NAME,gi.IMG_URL,gi.GOODS_PLACE,gi.GOODS_STATUS,");
		sb.append(" gi.GOODS_SPEC,CONCAT(gi.GOODS_SPEC,'斤装') as GOODS_SPEC_NAME,dict.DICT_NAME,p.SALE_PRICE,CONCAT('￥',p.SALE_PRICE,'元/件') as SALE_PRICE_NAME,(s.STORE_NUM-s.SALE_NUM) as STORE_NUM,(s.STORE_NUM-s.SALE_NUM) as STOCK");
		sb.append(" from goodsinfo gi");
		sb.append(" inner JOIN dictionary dict on dict.DICT_CODE=gi.GOODS_PACKING");
		sb.append(" inner JOIN price p on gi.GOODS_ID=p.GOODS_ID");
		sb.append(" inner JOIN store s on s.GOODS_ID=gi.GOODS_ID");
		sb.append(" where TO_DAYS(p.SET_DATE)=TO_DAYS(NOW()) AND TO_DAYS(s.SET_DATE)=TO_DAYS(NOW())");
		sb.append(" AND p.STATION_ID="+station_id);
		sb.append(" AND gi.GOODS_ID in("+goods_ids+")");
		try{
			List<Record> list = Db.find(sb.toString());
			System.out.println(list);
			result.put("data", JsonKit.toJson(list));
			JsonUtil.put(result, ReturnEnum.GOODS_LIST_SUCCESS);
		}catch(Exception ex){
			result.put("data", Lists.newArrayList());
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
		}
	}
	
	/**
	 * 菜篮子中查询所有商品的信息（含实时的库存和价格）
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'goods',type:'findgoodsinfo',station_id:'1',goods_id:'1'}
	 * http://112.124.127.38:8081/bcy/mobile/Interface?content={namespace:'goods',type:'findgoodsinfo',station_id:'1',goods_id:'1'}
	 * http://112.124.127.38:8081/bcy/mobile/Interface?content={namespace:'goods',type:'findgoodsinfo',goods_details:[{"station_id":"1","goods_id":"1"},{"station_id":"1","goods_id":"2"}]}
	 * order_pay_detail:[{"num":"1","goods_id":"1"},{"num":"1","goods_id":"2"}]
	 */
	public void findgoodsinfobyid(JSONObject messageObj, JSONObject result){
		String station_id=messageObj.getString("station_id");
		String goods_id=messageObj.getString("goods_id");
		if(station_id==null || station_id.equals("") || goods_id==null || goods_id.equals("")){
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
			return;		
		}
		Object goodsobj = messageObj.get("order_pay_detail");
		StringBuffer sb=new StringBuffer(" SELECT gi.GOODS_ID,gi.GOODS_NAME,gi.APP_NAME,gi.IMG_URL,gi.GOODS_PLACE,");
		sb.append(" CONCAT(gi.GOODS_SPEC,'斤装') as GOODS_SPEC,dict.DICT_NAME,p.SALE_PRICE,(s.STORE_NUM-s.SALE_NUM) as STORE_NUM");
		sb.append(" from goodsinfo gi");
		sb.append(" inner JOIN dictionary dict on dict.DICT_CODE=gi.GOODS_PACKING");
		sb.append(" inner JOIN price p on gi.GOODS_ID=p.GOODS_ID");
		sb.append(" inner JOIN store s on s.GOODS_ID=gi.GOODS_ID");
		sb.append(" where TO_DAYS(p.SET_DATE)=TO_DAYS(NOW()) AND TO_DAYS(s.SET_DATE)=TO_DAYS(NOW())");
		sb.append(" AND p.STATION_ID="+station_id);
		sb.append(" AND gi.GOODS_ID="+goods_id);
		try{
			List<Record> list = Db.find(sb.toString());
			result.put("data", JsonKit.toJson(list));
			JsonUtil.put(result, ReturnEnum.GOODS_LIST_SUCCESS);
		}catch(Exception ex){
			result.put("data", Lists.newArrayList());
			JsonUtil.put(result, ReturnEnum.RETURN_FAIL);
		}
	}
}
